package com.example.spring.demo.common.config;

import com.example.spring.demo.common.result.Result;
import com.example.spring.demo.common.error.CustomException;
import com.example.spring.demo.common.error.ErrorCodeEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2024/12/25 21:38
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    //处理自定义异常
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Result<?>> handleCustomException(CustomException ex, WebRequest request) {
        return new ResponseEntity<>(Result.error(ex.getErrorCode(), ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理所有其他未捕捉的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<?>> globalExceptionHandler(Exception ex, WebRequest request) {
        ErrorCodeEnum errorCodeEnum = ErrorCodeEnum.SYSTEM_ERROR;
        Result<?> result = Result.error(errorCodeEnum.getErrorCode(), ex.getMessage());
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
